define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        utils = require('js/utils/tools'),
        models = require('js/apps/op/models'),
        moment = require('moment'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');

    var MchListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click a.onClickDelete': 'toDelete',
        },
        initialize: function (options) {
            this.options = options;
            this.collection = new models.MchCollection();
            this.collection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        toDelete: function (e) {
            utils.deleteItem(e, this.collection);
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/mch/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            utils.getPaginator(this.options, this.collection.total, '#op/mch/');
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/MchList.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new MchListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
    var MchDetailView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click a.template-save': 'toSaveOrCreate',
        },
        initialize: function (options) {
            this.model = new models.Mch();
            if (options.id) {
                this.model.set('id', options.id);
            }
            this.model.bind('change reset', this.renderWithData, this);
            this.chnCollection = new models.ChannelCollection();
            this.chnCollection.bind('change reset remove', this.renderWithData, this);
            this.withdrawChnCollection = new models.WithdrawChannelCollection();
            this.withdrawChnCollection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        _getCurrentInputs: function () {
            var wechat_chn_ids = $('#inputWechatChns').val() || [],
                wechat_chns = [],
                wechat_notify_prefix = $('#inputWechatNotifyPrefix').val();
            _.each(wechat_chn_ids, function (chn_id) {
                wechat_chns.push(parseInt(chn_id, 10));
            });
            var alipay_chn_ids = $('#inputAlipayChns').val() || [],
                alipay_chns = [],
                alipay_notify_prefix = $('#inputAlipayNotifyPrefix').val();
            _.each(alipay_chn_ids, function (chn_id) {
                alipay_chns.push(parseInt(chn_id, 10));
            });
            var unionpay_chn_ids = $('#inputUnionpayChns').val() || [],
                unionpay_chns = [];
            _.each(unionpay_chn_ids, function (chn_id) {
                unionpay_chns.push(parseInt(chn_id, 10));
            });
            var qq_chn_ids = $('#inputQQChns').val() || [],
                qq_chns = [];
            _.each(qq_chn_ids, function (chn_id) {
                qq_chns.push(parseInt(chn_id, 10));
            });
            var jd_chn_ids = $('#inputJDChns').val() || [],
                jd_chns = [];
            _.each(jd_chn_ids, function (chn_id) {
                jd_chns.push(parseInt(chn_id, 10));
            });
            var recharge_card_chn_ids = $('#inputRechargeCardChns').val() || [],
                recharge_card_chns = [];
            _.each(recharge_card_chn_ids, function (chn_id) {
                recharge_card_chns.push(parseInt(chn_id, 10));
            });
            var test_chn_ids = $('#inputTestChns').val() || [],
                test_chns = [];
            _.each(test_chn_ids, function (chn_id) {
                test_chns.push(parseInt(chn_id, 10));
            });
            var withdraw_chn_ids = $('#inputWithdrawChns').val() || [],
                withdraw_chns = [];
            _.each(withdraw_chn_ids, function (chn_id) {
                withdraw_chns.push(parseInt(chn_id, 10));
            });
            var data = {
                'name': $('#inputName').val(),
                'service_conf': {
                    'wechat': {
                        'chns': wechat_chns,
                        'notify_prefix': wechat_notify_prefix
                    },
                    'alipay': {
                        'chns': alipay_chns,
                        'notify_prefix': alipay_notify_prefix
                    },
                    'unionpay': {
                        'chns': unionpay_chns,
                        'notify_prefix': ''
                    },
                    'qq': {
                        'chns': qq_chns,
                        'notify_prefix': ''
                    },
                    'jd': {
                        'chns': jd_chns,
                        'notify_prefix': ''
                    },
                    'recharge_card': {
                        'chns': recharge_card_chns,
                        'notify_prefix': ''
                    },
                    'test': {
                        'chns': test_chns,
                        'notify_prefix': ''
                    },
                    'withdraw_alipay': {
                        'chns': withdraw_chns,
                        'notify_prefix': ''
                    }
                }
            }
            return data;
        },
        toSaveOrCreate: function (e) {
            e.preventDefault();
            var isAllRight = utils.simpleCheck();
            if (!isAllRight) {
                notify.error('错误', '输入错误，请检验');
                return;
            }
            var attrs = this._getCurrentInputs();
            this.model.save(attrs, {
                patch: true,
                success: function (model, response) {
                    notify.success('提示', '保存成功！');
                    setTimeout(function () {
                        history.back();
                    }, 500);
                },
                error: function (model, response) {
                    notify.notifyResp(response);
                }
            });
            return false;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                info: this.model.toJSON(),
                channels: this.chnCollection.toJSON(),
                withdraw_channels: this.withdrawChnCollection.toJSON()
            }));
            $('.date-box').datetimepicker({
                format: 'YYYY-MM-DD'
            });
            utils.multiselect('#inputWechatChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputAlipayChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputUnionpayChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputQQChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputJDChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputRechargeCardChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputTestChns', true, {
                'includeSelectAllOption': true
            });
            utils.multiselect('#inputWithdrawChns', true, {
                'includeSelectAllOption': true
            });
        },
        load: function () {
            this.chnCollection.fetch({
                reset: true,
                data: {
                    "mch_id": this.model.id || 0,
                    "$size": -1
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                },
            });
            this.withdrawChnCollection.fetch({
                reset: true,
                data: {
                    "mch_id": this.model.id || 0,
                    "$size": -1
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                },
            });
            if (this.model.id) {
                this.model.fetch({
                    reset: true
                });
            } else {
                this.renderWithData();
            }
        }
    });
    exports.Detail = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/MchDetail.html",
        initialize: function (id) {
            this.id = id;
        },
        render: function () {
            var view = new MchDetailView(this.id);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
});
